經過這兩天的實作洗禮,發現自己卡在css上的時間遠比想像來的久。為了加速開發,今天我們來探討css預處理器—Sass,看看是否能幫我突破困境!
Sass提供指令碼與程式的邏輯,像是變數、迴圈…等,讓我們撰寫css。特點是能夠處理重複的元素、達成更複雜的指令,再經由直譯器轉成網頁讀得懂的css檔案,因此能看作css預處理器或是css的擴充工具。除此之外,Sass利用模組化的概念以命名空間讓我們可以引用其他.sass或.scss檔案!
大括號{ }及每行結尾後方的分號;,還有嚴謹的縮排格式並透過換行的方式將不同的規則區隔,也稱為縮排語法:li
  width: 100%
  height: 50px
  list-style: none
  padding: 13px
  cursor: pointer
  background-color: #ffffff
  &:hover
    background-color: #cacaca
li{
  width: 100%;
  height: 50px;
  list-style: none;
  padding: 13px;
  cursor: pointer;
  background-color: #ffffff;
  &:hover{
    background-color: #cacaca;
  }
}
轉譯為css的結果:
li {
  width: 100%;
  height: 50px;
  list-style: none;
  padding: 13px;
  cursor: pointer;
  background-color: #ffffff;
}
li :hover {
  background-color: #cacaca;
}
目前還滿好理解的,透過巢狀的塊語法看起來更有相關性了,以下我們選用SCSS語法(以下代稱)接續練習!
用$字號宣告變數,:指定參數:
$no-display:none;
$mouse-status:pointer;
ul {
  width: 85%;
  height: 300px;
  overflow-y: auto;
  margin-top: 20px;
  scrollbar-width: thin;
  padding: inherit;
  li{
    width: 100%;
    height: 50px;
    list-style: $no-display;
    padding: 13px;
    cursor: $mouse-status;
    background-color: #ffffff;
    &:hover{
      background-color: #cacaca;
    }
  }
  button {
      background: $no-display;
      border: $no-display;
      cursor: $mouse-status;
  }
}
假設有a,b兩個檔案,a檔案宣告變數,b檔案可以透過引用模組跨檔案使用變數,輸出結果會將兩者合併:
//a_file.scss
$dark-color:#808080;
div {
    margin-top: 15px;
    border-bottom: 1px solid $dark-color;
    width: 100%
}
//b_file.scss
@use 'a_file';
button {
    border: none;
    background-color: #ffffff;
    margin-left: 10px;
    color: a_file.$dark-color;
    cursor: pointer;
    padding: .375rem .75rem
}
當需要使用多個重複屬性、參數可以變換,就能透過Mixin進行混合的動作:
@mixin theme($color1: #808080,$color2:white) {
  border: none;
  background-color: $color1;
  margin-left: 10px;
  color: $color2;
  cursor: pointer;
  padding: .375rem .75rem;
}
.add_item {
  @include theme;
}
.nav_item {
  @include theme($color1:white,$color2:#808080);
}
使用%像群組一樣打包重複樣式,透過@extend引用:
%btn_icon {
  background: none;
  border: none;
  cursor: pointer;
}
.btn_finish .btn_check{
  @extend %btn_icon;
  float:left;
}
.btn_delete{
  @extend %btn_icon;
  float:right;
}
.btn_save{
  @extend %btn_icon;
  color:green;
  margin-right:5px
}
.btn_cancle{
  @extend %btn_icon;
  color:darkred;
}
再進階一點,我們也可以透過@function或@use "sass:math"進行參數的計算:
$font:6px 8px 10px 12px; //這裡的陣列起始為1
$margin:1px 3px;
@function font($index){
  @return nth($font,$index)*5;
}
@function margin($index){
  @return nth($margin,$index)*20;
}
.btn{
  font-size:font(2); 
  margin:margin(1);
}
@use "sass:math";
.btn{
  font-size:math.div(20px,40px)*10%; 
  margin:math.floor(45.6)*2px;
}